package com.halixun.d2app.printer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;


import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.halixun.d2app.app.MyApplication;
import com.halixun.d2app.base.BasePrintInfo;
import com.halixun.d2app.bean.FoodCategoryInfo;
import com.halixun.d2app.bean.OrderListInfo;
import com.halixun.d2app.bean.PrinterInfo;
import com.halixun.d2app.bean.QingDanInfo;
import com.halixun.d2app.bean.print.NetPrintInfo;
import com.halixun.d2app.bean.print.UsbPrintInfo;
import com.halixun.d2app.utils.DataOperationUtil;
import com.halixun.d2app.utils.DateUtil;
import com.halixun.d2app.utils.Pos;
import com.halixun.d2app.utils.PrintReceiptsUtil;
import com.halixun.d2app.utils.RunningWaterUtil;

import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ProjectName: MyOrderSystem
 * @Package: com.hlddl.order.printer
 * @ClassName: PrinterUtils
 * @Description: 调用打印机打印
 * @Author: hdx
 * @CreateDate: 2019/10/18 17:02
 * @UpdateUser: hdx
 * @UpdateDate: 2019/10/18 17:02
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class PrinterUtils {

    /**
     * 打印纸一行最大的字节
     */
    private static final int LINE_BYTE_SIZE = 32;

    /**
     * 打印三列时，中间一列的中心线距离打印纸左侧的距离
     */
    private static final int LEFT_LENGTH = 16;

    /**
     * 打印三列时，中间一列的中心线距离打印纸右侧的距离
     */
    private static final int RIGHT_LENGTH = 16;

    /**
     * 打印三列时，第一列汉字最多显示几个文字
     */
    private static final int LEFT_TEXT_MAX_LENGTH = 5;

    private static ExecutorService singleThreadExecutorByNet = Executors.newSingleThreadExecutor();

    private static ExecutorService singleThreadExecutorByUsb = Executors.newSingleThreadExecutor();


    public static void print(List<OrderListInfo> infos, String orderCode, int payType) {
        if (infos == null || infos.size() == 0) return;
        PrintReceiptsUtil.resetTime();
        String oddNumber = RunningWaterUtil.getRunning_water();
        String orderTime = DateUtil.getDateToString2(System.currentTimeMillis() / 1000);
        PrinterInfo printerInfo = new PrinterInfo();
        List<PrinterInfo.PrinterFootInfo> list = new ArrayList<>();
        for (OrderListInfo info : infos) {
            PrinterInfo.PrinterFootInfo printerFootInfo = new PrinterInfo.PrinterFootInfo();
            printerFootInfo.commodityNumber = info.getCommodityNumber();
            printerFootInfo.Price = info.getPrice();
            printerFootInfo.Title = info.getTitle();
            printerFootInfo.classID = info.getClassID();
            list.add(printerFootInfo);
        }
        printerInfo.mFootInfos = list;
        printerInfo.oddNumber = oddNumber;
        printerInfo.orderCode = orderCode;
        printerInfo.orderTime = orderTime;
        printerInfo.payType = payType;
        printByUsb(printerInfo);
        printByNet(printerInfo);
    }


    private static void printByNet(PrinterInfo printerInfo) {
        List<NetPrintInfo> netPrintInfos = PrintReceiptsUtil.getNetPrint();
        if (netPrintInfos != null) {
            for (NetPrintInfo info : netPrintInfos) {
                if (info.isPrint) {
                    if (!TextUtils.isEmpty(info.ip) && info.port != 0) {
                        if (info.isFractionToPrint) {
                            fractionPrintByNet(printerInfo, info.ip, info.port, info);
                        } else {
                            jewelsPrintByNet(printerInfo, info.ip, info.port, info);
                        }
                    }
                }
            }
        }
    }

    private static void printByUsb(PrinterInfo printerInfo) {
        USBPrinter usbPrinter = USBPrinter.getInstance();
        if (!usbPrinter.getInitState()) {
            usbPrinter.initPrinter();
        }
        List<UsbPrintInfo> availablePrintInfos = MyApplication.getUsbPrintList();
        if (availablePrintInfos.size() == 0) return;
        Log.e("printByUsb1", new Gson().toJson(availablePrintInfos));
        for (UsbPrintInfo usbPrintInfo : availablePrintInfos) {
            Log.e("printByUsb2", new Gson().toJson(usbPrintInfo));
            if (usbPrintInfo.isPrint) {
                if (usbPrintInfo.isFractionToPrint) {
                    fractionPrintByUsb(printerInfo, usbPrinter, usbPrintInfo);
                } else {
                    jewelsPrintByUsb(printerInfo, usbPrinter, usbPrintInfo);
                }
            }
        }
    }

    /**
     * 网络打印(和式打印)
     */
    private static void jewelsPrintByNet(PrinterInfo printerInfo, String ip, int port, NetPrintInfo netPrintInfo) {
        Log.e("PrinterUtils", "jewelsPrintByNet网络打印(和式打印)1");
        List<PrinterInfo.PrinterFootInfo> printerFootInfos = new ArrayList<>();
        if (netPrintInfo.mFoodCategoryInfos != null && netPrintInfo.mFoodCategoryInfos.size() > 0) {
            for (PrinterInfo.PrinterFootInfo footInfo : printerInfo.mFootInfos) {
                for (FoodCategoryInfo categoryInfo : netPrintInfo.mFoodCategoryInfos) {
                    if (footInfo.classID == categoryInfo.getID()) {
                        printerFootInfos.add(footInfo);
                    }
                }
            }
            Log.e("PrinterUtils", "printerFootInfos==" + new Gson().toJson(printerFootInfos));
            if (printerFootInfos.size() == 0) {
                return;
            }
        }
        Log.e("PrinterUtils", "jewelsPrintByNet网络打印(和式打印)2");
        Log.e("PrinterUtils", "jewelsPrintByNet" + new Gson().toJson(printerFootInfos.size() == 0 ? printerInfo.mFootInfos : printerFootInfos));
        singleThreadExecutorByNet.execute(() -> {
            Pos pos = null;
            try {
                pos = new Pos(ip, port, "gbk");
                pos.initPos();
                pos.setTextSize(2);
                pos.printLocation(1);
                pos.printTextNewLine("收银凭证");
                pos.printLine(1);
                pos.printTextNewLine("单据: " + printerInfo.oddNumber);
                pos.printLine(1);
                pos.printLocation(0);
                pos.setTextSize(0);
                pos.printTextNewLine("收单单据：" + printerInfo.orderCode);
                pos.printTextNewLine("下单时间：" + printerInfo.orderTime);
                if (printerInfo.payType == 7) {
                    pos.printTextNewLine("支付方式：现金支付");
                }
                pos.printLine(1);
                pos.printText("--------------------------------");
                pos.printTextNewLine(printThreeData("商品名称", "单价", "总计"));
                pos.printTextNewLine("--------------------------------");
                double tPrice = 0;
                if (printerFootInfos.size() == 0) {
                    for (PrinterInfo.PrinterFootInfo info : printerInfo.mFootInfos) {
                        double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                        tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                        pos.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi));
                    }
                } else {
                    for (PrinterInfo.PrinterFootInfo info : printerFootInfos) {
                        double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                        tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                        pos.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi));
                    }
                }
                pos.printTextNewLine("--------------------------------");
                pos.printTextNewLine("实收：" + tPrice);
                pos.printTextNewLine("--------------------------------");
                pos.printTextNewLine("谢谢惠顾!");
                pos.printLine(3);
                pos.feedAndCut();
                pos.closeIOAndSocket();
                pos = null;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                Log.e("jewelsPrintByNet", "错误信息1：" + e.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("jewelsPrintByNet", "错误信息2：" + e.toString());
            } finally {
                if (null != pos) {
                    try {
                        pos.closeIOAndSocket();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        pos = null;
                    }
                }
            }
        });
    }


    /**
     * usb打印（合式打印）
     */
    private static void jewelsPrintByUsb(PrinterInfo printerInfo, USBPrinter usbPrinter, UsbPrintInfo usbPrintInfo) {
        Log.e("PrinterUtils", "jewelsPrintByUsb usb打印（合式打印）");
        Log.e("printByUsb3", new Gson().toJson(usbPrintInfo));
        List<PrinterInfo.PrinterFootInfo> printerFootInfos = new ArrayList<>();
        if (usbPrintInfo.mFoodCategoryInfos != null && usbPrintInfo.mFoodCategoryInfos.size() > 0) {
            for (PrinterInfo.PrinterFootInfo footInfo : printerInfo.mFootInfos) {
                for (FoodCategoryInfo categoryInfo : usbPrintInfo.mFoodCategoryInfos) {
                    if (footInfo.classID == categoryInfo.getID()) {
                        printerFootInfos.add(footInfo);
                    }
                }
            }
            if (printerFootInfos.size() == 0) {
                return;
            }
        }
        singleThreadExecutorByUsb.execute(() -> {
            usbPrinter.setTextSize(2, usbPrintInfo);
            usbPrinter.setAlign(1, usbPrintInfo);
            usbPrinter.printTextNewLine("收银凭证", usbPrintInfo);
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.printTextNewLine("单据: " + printerInfo.oddNumber, usbPrintInfo);
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.setAlign(0, usbPrintInfo);
            usbPrinter.setTextSize(0, usbPrintInfo);
            usbPrinter.printTextNewLine("收单单据：" + printerInfo.orderCode, usbPrintInfo);
            usbPrinter.printTextNewLine("下单时间：" + printerInfo.orderTime, usbPrintInfo);
            if (printerInfo.payType == 7) {
                usbPrinter.printTextNewLine("支付方式：现金支付", usbPrintInfo);
            }
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.printText("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine(printThreeData("商品名称", "单价", "总计"), usbPrintInfo);
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            double tPrice = 0;
            if (printerFootInfos.size() == 0) {
                for (PrinterInfo.PrinterFootInfo info : printerInfo.mFootInfos) {
                    double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                    tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                    usbPrinter.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi), usbPrintInfo);
                }
            } else {
                for (PrinterInfo.PrinterFootInfo info : printerFootInfos) {
                    double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                    tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                    usbPrinter.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi), usbPrintInfo);
                }
            }
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine("实收：" + tPrice, usbPrintInfo);
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine("谢谢惠顾!", usbPrintInfo);
            usbPrinter.printLine(3, usbPrintInfo);
            usbPrinter.cutPager(usbPrintInfo);
        });
    }


    /**
     * 网络打印（分式打印）
     */
    private static void fractionPrintByNet(PrinterInfo printerInfo, String ip, int port, NetPrintInfo netPrintInfo) {
        Log.e("PrinterUtils", "fractionPrintByNet网络打印（分式打印）");
        Map<Integer, List<PrinterInfo.PrinterFootInfo>> map = new HashMap<>();
        for (PrinterInfo.PrinterFootInfo info : printerInfo.mFootInfos) {
            if (map.containsKey(info.classID)) {
                List<PrinterInfo.PrinterFootInfo> value = map.get(info.classID);
                if (null != value) {
                    if (!value.contains(info)) {
                        value.add(info);
                    }
                } else {
                    value = new ArrayList<>();
                    value.add(info);
                    map.put(info.classID, value);
                }
            } else {
                List<PrinterInfo.PrinterFootInfo> list = new ArrayList<>();
                list.add(info);
                map.put(info.classID, list);
            }
        }

        List<List<PrinterInfo.PrinterFootInfo>> infos = new ArrayList<>();
        for (List<PrinterInfo.PrinterFootInfo> info : map.values()) {
            infos.add(info);
        }
        long time = netPrintInfo.fractionToPrintIntervalTime;
        if (time == 0) {
            for (List<PrinterInfo.PrinterFootInfo> info : infos) {
                printFootByNet(info, printerInfo, ip, port, netPrintInfo);
            }
        } else {
            @SuppressLint("HandlerLeak") Handler handler = new Handler() {

                int position = 0;

                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    position += 1;
                    if (position <= infos.size()) {
                        printFootByNet(infos.get(position - 1), printerInfo, ip, port, netPrintInfo);
                        Message message = obtainMessage();
                        message.what = 2;
                        sendMessageDelayed(message, time);
                    } else {
                        position = 0;
                        removeCallbacksAndMessages(null);
                    }
                }
            };
            handler.sendEmptyMessage(1);
        }
    }

    /**
     * usb打印(分式打印)
     */
    private static void fractionPrintByUsb(PrinterInfo printerInfo, USBPrinter usbPrinter, UsbPrintInfo usbPrintInfo) {
        Map<Integer, List<PrinterInfo.PrinterFootInfo>> map = new HashMap<>();
        for (PrinterInfo.PrinterFootInfo info : printerInfo.mFootInfos) {
            if (map.containsKey(info.classID)) {
                List<PrinterInfo.PrinterFootInfo> value = map.get(info.classID);
                if (null != value) {
                    if (!value.contains(info)) {
                        value.add(info);
                    }
                } else {
                    value = new ArrayList<>();
                    value.add(info);
                    map.put(info.classID, value);
                }
            } else {
                List<PrinterInfo.PrinterFootInfo> list = new ArrayList<>();
                list.add(info);
                map.put(info.classID, list);
            }
        }

        List<List<PrinterInfo.PrinterFootInfo>> infos = new ArrayList<>();
        for (List<PrinterInfo.PrinterFootInfo> info : map.values()) {
            infos.add(info);
        }
        Log.e("PrinterUtils", "fractionPrintByUsb usb打印(分式打印)");
        long time = usbPrintInfo.fractionToPrintIntervalTime;
        Log.e("printByUsb3", new Gson().toJson(usbPrintInfo));
        if (time == 0) {
            for (List<PrinterInfo.PrinterFootInfo> info : infos) {
                printFootByUsb(info, printerInfo, usbPrinter, usbPrintInfo);
            }
        } else {
            @SuppressLint("HandlerLeak") Handler handler = new Handler() {

                int position;

                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    position += 1;
                    if (position <= infos.size()) {
                        printFootByUsb(infos.get(position - 1), printerInfo, usbPrinter, usbPrintInfo);
                        Message message = obtainMessage();
                        message.what = 2;
                        sendMessageDelayed(message, time);
                    } else {
                        position = 0;
                        removeCallbacksAndMessages(null);
                    }
                }
            };
            handler.sendEmptyMessage(1);
        }
    }

    /**
     * 分别打印一个商品(网络打印)
     *
     * @param infos
     */
    private static void printFootByNet(List<PrinterInfo.PrinterFootInfo> infos, PrinterInfo printerInfo, String ip, int port, NetPrintInfo netPrintInfo) {
        if (!isForbid(infos, netPrintInfo)) {
            Log.e("PrinterUtils", "printFootByNet分别打印一个商品(网络打印)1");
            return;
        }
        Log.e("PrinterUtils", "printFootByNet" + new Gson().toJson(infos));
        singleThreadExecutorByNet.execute(() -> {
            Pos pos = null;
            try {
                pos = new Pos(ip, port, "gbk");
                pos.initPos();
                pos.setTextSize(2);
                pos.printLocation(1);
                pos.printTextNewLine("收银凭证");
                pos.printLine(1);
                pos.printTextNewLine("单据: " + printerInfo.oddNumber);
                pos.printLine(1);
                pos.printLocation(0);
                pos.setTextSize(0);
                pos.printTextNewLine("收单单据：" + printerInfo.orderCode);
                pos.printTextNewLine("下单时间：" + printerInfo.orderTime);
                if (printerInfo.payType == 7) {
                    pos.printTextNewLine("支付方式：现金支付");
                }
                pos.printLine(1);
                pos.printText("--------------------------------");
                pos.printTextNewLine(printThreeData("商品名称", "单价", "总计"));
                pos.printTextNewLine("--------------------------------");
                double tPrice = 0;
                for (PrinterInfo.PrinterFootInfo info : infos) {
                    double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                    tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                    pos.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi));
                }
                pos.printTextNewLine("--------------------------------");
                pos.printTextNewLine("实收：" + tPrice);
                pos.printTextNewLine("--------------------------------");
                pos.printTextNewLine("谢谢惠顾!");
                pos.printLine(3);
                pos.feedAndCut();
                pos.closeIOAndSocket();
                pos = null;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                Log.d("tag", "错误信息1：" + e.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("tag", "错误信息2：" + e.toString());
            } finally {
                if (null != pos) {
                    try {
                        pos.closeIOAndSocket();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        pos = null;
                    }
                }
            }
        });
    }

    /**
     * 分别打印一个商品(usb打印)
     */
    private static void printFootByUsb(List<PrinterInfo.PrinterFootInfo> infos, PrinterInfo printerInfo, USBPrinter usbPrinter, UsbPrintInfo usbPrintInfo) {
        if (!isForbid(infos, usbPrintInfo)) {
            Log.e("PrinterUtils", "printFootByUsb分别打印一个商品(usb打印)1");
            return;
        }
        Log.e("PrinterUtils", "printFootByUsb" + new Gson().toJson(infos));
        singleThreadExecutorByUsb.execute(() -> {
            usbPrinter.setTextSize(2, usbPrintInfo);
            usbPrinter.setAlign(1, usbPrintInfo);
            usbPrinter.printTextNewLine("收银凭证", usbPrintInfo);
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.printTextNewLine("单据: " + printerInfo.oddNumber, usbPrintInfo);
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.setAlign(0, usbPrintInfo);
            usbPrinter.setTextSize(0, usbPrintInfo);
            usbPrinter.printTextNewLine("收单单据：" + printerInfo.orderCode, usbPrintInfo);
            usbPrinter.printTextNewLine("下单时间：" + printerInfo.orderTime, usbPrintInfo);
            if (printerInfo.payType == 7) {
                usbPrinter.printTextNewLine("支付方式：现金支付", usbPrintInfo);
            }
            usbPrinter.printLine(1, usbPrintInfo);
            usbPrinter.printText("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine(printThreeData("商品名称", "单价", "总计"), usbPrintInfo);
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            double tPrice = 0;
            for (PrinterInfo.PrinterFootInfo info : infos) {
                double xiaoJi = DataOperationUtil.mul(info.Price, info.commodityNumber);
                tPrice = DataOperationUtil.add(tPrice, xiaoJi);
                usbPrinter.printTextNewLine(printThreeData(info.Title, info.Price + " X " + info.commodityNumber, "" + xiaoJi), usbPrintInfo);
            }
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine("实收：" + tPrice, usbPrintInfo);
            usbPrinter.printTextNewLine("--------------------------------", usbPrintInfo);
            usbPrinter.printTextNewLine("谢谢惠顾!", usbPrintInfo);
            usbPrinter.printLine(3, usbPrintInfo);
            usbPrinter.cutPager(usbPrintInfo);
        });
    }

    public static boolean isForbid(List<PrinterInfo.PrinterFootInfo> infos, BasePrintInfo netPrintInfo) {
        if (null != netPrintInfo.mFoodCategoryInfos && netPrintInfo.mFoodCategoryInfos.size() > 0) {
            for (FoodCategoryInfo categoryInfo : netPrintInfo.mFoodCategoryInfos) {
                for (PrinterInfo.PrinterFootInfo info : infos) {
                    if (categoryInfo.getID() == info.classID) {
                        return true;
                    }
                }
            }
            return false;
        } else {
            return true;
        }
    }


    /**
     * 打印报表
     */
    public static void printOrder(List<QingDanInfo> infos) {
        singleThreadExecutorByUsb.execute(() -> {
            USBPrinter usbPrinter = USBPrinter.getInstance();
            if (!usbPrinter.getInitState()) {
                usbPrinter.initPrinter();
            }
            if (!usbPrinter.isHasUSBPrinter()) return;
            usbPrinter.setAlign(0, null);
            usbPrinter.setTextSize(0, null);
            usbPrinter.printText("--------------------------------", null);
            usbPrinter.printTextNewLine(printThreeData("商品名称", "数目", "总计"), null);
            usbPrinter.printTextNewLine("--------------------------------", null);
            double tPrice = 0;
            for (QingDanInfo info : infos) {
                tPrice = DataOperationUtil.add(tPrice, info.getSaleMoney());
                usbPrinter.printTextNewLine(printThreeData(info.getFoodName(), info.getSaleNum() + "", "" + info.getSaleMoney()), null);
            }
            usbPrinter.printTextNewLine("--------------------------------", null);
            usbPrinter.printTextNewLine("实收：" + tPrice, null);
            usbPrinter.printTextNewLine("--------------------------------", null);
            usbPrinter.printTextNewLine("谢谢惠顾!", null);
            usbPrinter.printLine(3, null);
            usbPrinter.cutPager(null);
        });
    }


    private static String getKongGe(int lenght, int position) {
        String value = "";
        if (position > lenght) {
            for (int i = 0; i < (position - lenght) * 2; i++) {
                value = value + " ";
            }
        }
        return value;
    }

    /**
     * 打印两列
     *
     * @param leftText  左侧文字
     * @param rightText 右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printTwoData(String leftText, String rightText) {
        StringBuilder sb = new StringBuilder();
        int leftTextLength = getBytesLength(leftText);
        int rightTextLength = getBytesLength(rightText);
        sb.append(leftText);

        // 计算两侧文字中间的空格
        int marginBetweenMiddleAndRight = LINE_BYTE_SIZE - leftTextLength - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }
        sb.append(rightText);
        return sb.toString();
    }

    /**
     * 打印三列
     *
     * @param leftText   左侧文字
     * @param middleText 中间文字
     * @param rightText  右侧文字
     * @return
     */
    @SuppressLint("NewApi")
    public static String printThreeData(String leftText, String middleText, String rightText) {
        StringBuilder sb = new StringBuilder();
        // 左边最多显示 LEFT_TEXT_MAX_LENGTH 个汉字 + 两个点
        if (leftText.length() > LEFT_TEXT_MAX_LENGTH) {
            leftText = leftText.substring(0, LEFT_TEXT_MAX_LENGTH) + "..";
        }
        int leftTextLength = getBytesLength(leftText);
        int middleTextLength = getBytesLength(middleText);
        int rightTextLength = getBytesLength(rightText);

        sb.append(leftText);
        // 计算左侧文字和中间文字的空格长度
        int marginBetweenLeftAndMiddle = LEFT_LENGTH - leftTextLength - middleTextLength / 2;

        for (int i = 0; i < marginBetweenLeftAndMiddle; i++) {
            sb.append(" ");
        }
        sb.append(middleText);

        // 计算右侧文字和中间文字的空格长度
        int marginBetweenMiddleAndRight = RIGHT_LENGTH - middleTextLength / 2 - rightTextLength;

        for (int i = 0; i < marginBetweenMiddleAndRight; i++) {
            sb.append(" ");
        }

        // 打印的时候发现，最右边的文字总是偏右一个字符，所以需要删除一个空格
        sb.delete(sb.length() - 1, sb.length()).append(rightText);
        return sb.toString();
    }

    /**
     * 获取数据长度
     *
     * @param msg
     * @return
     */
    @SuppressLint("NewApi")
    private static int getBytesLength(String msg) {
        return msg.getBytes(Charset.forName("GB2312")).length;
    }

}
